import {Message, Contact, Wechaty, Room} from 'wechaty'
import { BotMsg } from '../entity/BotMsg';
import { DefaultBotContact } from '../entity/DefaultBotContact';
import { RoomContact } from '../entity/RoomContact';
const request =  require('request')
export async function handleMessage(message: Message, bot: Wechaty){
  const botMsg = new BotMsg();
  const contact = message.talker()
  const text = message.text()
  const toContact = message.to()
  if (toContact) {
    const name = toContact.name()
    botMsg.toUserName = name
    console.log(`toContact: ${name} Contact: ${contact.name()} Text: ${text}`)
  } else {
    console.log(`Contact: ${contact.name()} Text: ${text}`)
  }
  if(contact){
    botMsg.formUserName = contact.name()
  }
  let room = message.room()
  if (room) {
    const oldTopic = await room.topic()
    botMsg.roomName = oldTopic
    const roomJson = JSON.stringify(room)
    botMsg.roomId = room.id
    getContactAllByRoom(room)
    // console.log('room jsonInfo:', roomJson)
    // await room.topic('change topic to wechaty!')
  }
  botMsg.msgText = text
  await botMsg.save();

  if(text.startsWith("建群:") && !contact.self()){
    createRoomTopic(contact, text.substring(3, text.length), bot)
  }

}
/**
 * 获取所有联系人信息
 * @param room 
 */
 function getContactAllByRoom(room: Room){
  let contactMap = new Map()
  RoomContact.find({}).then((dataList:RoomContact[])=>{
    dataList.forEach((item)=>{
      contactMap.set(item.roomId + item.contactId, item.contactId)
    })
  })
  room.memberAll().then(contacList =>{
    contacList.forEach(async contact =>{
      if(!contact.self()){ //不是本人
        if(contactMap.get(room.id + contact.id) === undefined){
          let rc = new RoomContact()
          rc.roomId = room.id
          rc.roomName = await room.topic()
          rc.contactId = contact.id
          rc.contactName = contact.name()
          rc.isFriend = contact.friend()
          rc.province = await contact.province()
          rc.city = contact.city()
          rc.weixin = contact.weixin()
          let phoneList = await contact.phone()
          if(phoneList && phoneList.length > 0){
            rc.phone = contact.phone()[0]
          }
          rc.avatar = (await contact.avatar()).name
          rc.save()
        }
      }
    })
  })
}

export function receivePayInfo(msg: Message, bot: Wechaty) {
  const contact = msg.talker()
  if ( msg.type() !== bot.Message.Type.Attachment && !msg.self()
    || contact.name() !== '微信支付') {
    return
  }
  const strs = msg.text().split('元')
  if (strs.length >= 1) {
    const prices = strs[0].split('微信支付收款')
    if (prices.length >= 1) {
      const priceStr = prices[1]
      sendPayment(parseFloat(priceStr), msg.date().getTime())
    }
  }
}

// 收到金额之后，进行确认订单回调 
function sendPayment (priceAmount, timestamp) {
  const options = {
    method: 'POST',
    url: 'https://api.callbackaddress.com/api/admin/callback',
    headers: { 'content-type': 'application/json', 'token': 'XXXXXX'},
    body: {'amount': priceAmount, 'timestamp': timestamp },
    json: true 
  };
  console.log('requset options', options)
  request(options, function (error, response, body) {
    if (error) {
      console.log(error)
    }
  });
}
/**
 * 群信息
 * @param bot 
 */
export function getAllRoomInfo(bot : Wechaty){
  bot.Room.findAll().then((roomList)=>{
    roomList.forEach(item =>{
      console.log(item.topic())
    })
  })
}
/**
 * 创建群聊
 * @param contact 
 * @param topicName 
 */
export async function createRoomTopic(contact: Contact,topicName: string, bot : Wechaty){
  let dataList = await DefaultBotContact.find()
  await dataList.forEach(async item=>{
    let contactItem = await bot.Contact.find({ name: item.contactName})
    const contactList = [contact, contactItem]
    const room = await bot.Room.create(contactList, 'ding')
    console.log('Bot', 'createDingRoom() new ding room created: "%s"', room)

    await room.topic('ding - created')
    await room.say('ding - created')
  })
}

// 定时执行
setInterval(function() {

  console.log('send msg')
},1000 * 60 * 10)
